import 'package:app/api/menu/index.dart';
import 'package:app/util/ColorUtil.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import '../../components/index.dart';
import '../../api/account/index.dart';
import 'package:app/page/home/mine.dart';

class Home extends StatefulWidget{

  final String? userName;

  const Home({super.key, this.userName});

  @override
  State<StatefulWidget> createState()  => _HomeState(userName);

}

/// 首页
class _HomeState extends State<Home>{

  final String? userName;

  _HomeState(this.userName);

  List<dynamic> _menus = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      menus();
    });
  }

  /// 获取用户菜单
  menus(){
    MenuApi.of(context).menus().then((res){
      if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
        setState(()=> _menus = res.data['data']);
      }
    });
  }

  void go(String path){
    Navigator.pushNamed(context, path).then((_){
      menus();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Header(userName: userName),
          Expanded(
              child: ListView.builder(
                  padding: EdgeInsets.zero,
                  itemCount: 1,
                  itemBuilder: (context, index){
                    return  Menu(
                      context: context,
                      items: _menus.map((item) => MenuItem(
                        icon: Icon(IconData(int.parse(item['icon']), fontFamily: 'MaterialIcons'), color: Colors.white,size: 40),
                        text: item['name'],
                        color: ColorUtil.stringColor(item['color'], alpha: 1),
                        onTap: () => go(item['path']),
                      )).toList(),
                    );
                  }
              )
          )
        ],
      ),
    );
  }
}